package com.twu.biblioteca;

import org.jbcrypt.BCrypt;

import java.util.ArrayList;

public class User {

    private static ArrayList<User> users = new ArrayList<User>();
    private String hashedPassword;
    private String libraryNumber;

    private String name;
    private String email;
    private String address;
    private String phone;

    public User(String libraryNumber, String plaintextPassword) {
        this.libraryNumber = libraryNumber;
        this.hashedPassword = BCrypt.hashpw(plaintextPassword, BCrypt.gensalt());
        users.add(this);
    }

    public static User authenticate(String libraryNumber, String plainTextPassword) {
        User user = findUser(libraryNumber);
        if (user == null) {
            return null;
        } else {
            if (user.isValidPassword(plainTextPassword)) {
                return user;
            } else {
                return null;
            }
        }
    }

    public boolean equals(Object other) {
        if (other instanceof User) {
            User otherUser = (User) other;
            return this.getLibraryNumber().equals(otherUser.getLibraryNumber());
        } else {
            return false;
        }
    }

    public String getLibraryNumber() {
        return this.libraryNumber;
    }

    private static User findUser(String libraryNumber) {
        User foundUser = null;
        for (User user : users) {
            if (user.getLibraryNumber().equals(libraryNumber)) {
                foundUser = user;
                break;
            }
        }
        return foundUser;
    }

    public String toString() {
        String userString = "";
        userString += "Library Number:" + this.getLibraryNumber() + "\n";
        userString += "Name: " + this.getName() + "\n";
        userString += "Email: " + this.getEmail() + "\n";
        userString += "Address: " + this.getAddress() + "\n";
        userString += "Phone: " + this.getPhone() + "\n";
        return userString;
    }

    public String info() {
        return this.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    private boolean isValidPassword(String plaintextPassword) {
        return BCrypt.checkpw(plaintextPassword, this.hashedPassword);
    }

}
